﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using DataAccess.DataObject;
using DataAccess.BusinessObject;
using System.Globalization;
using System.Threading;
using System.Net.Configuration;


namespace EnmineKaitlin.admin
{
    public partial class post_new : Common.PageBase
    {                        
        int PostID = 0;
        const string module = "manage-post";
        protected void Page_Load(object sender, EventArgs e)
        {
            if(CheckPermission(module))
            {
            if (!IsPostBack)
            {
                try
                {
                    if (Request["p"] != null)
                    {
                        PostID = int.Parse(Request["p"].ToString());
                    }                
                    if (PostID > 0)
                    {
                        if (Request["post_type"] != null && Request["post_type"].ToString() == "page")
                        {
                            PostID = int.Parse(Request["p"].ToString());
                            lblFunction.Text = "Cập nhật bài viết";
                            pnlAddPost.Visible = false;
                            pnlEditPost.Visible = true;
                            rptDetailPage.DataSource = _BPost.Get(PostID);
                            rptDetailPage.DataBind();
                        }
                        else
                        {
                            PostID = int.Parse(Request["p"].ToString());
                            lblFunction.Text = "Cập nhật bài viết";
                            pnlAddPost.Visible = false;
                            pnlEditPost.Visible = true;
                            BindDetailPost(PostID);
                        }
                    }
                    else
                    {
                        if (Request["post_type"] != null && Request["post_type"].ToString() == "page")
                        {
                            lblFunction.Text = "Thêm trang";
                            pnlExcerpt.Visible = false;
                            pnlCategory.Visible = false;
                            pnlFeaturedImage.Visible = false;
                            txtCreateDate.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                            btnAdd.Text = "Đăng bài viết";
                            btnAdd.DataBind();
                            bindckeditor(ckeContent);
                        }
                        else
                        {
                            lblFunction.Text = "Thêm bài viết";
                            txtCreateDate.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                            btnAdd.Text = "Đăng bài viết";
                            btnAdd.DataBind();
                            bindckeditor(ckeContent);
                            BindCategory(cblCategory, 0, -1, "vn");
                        }
                    }
                }            
                catch (Exception ex)
                { 
                    Response.Redirect("~/admin/Default.aspx");
                }   
            }
            }
            else
            {
                Response.Redirect("~/admin/permission-fail.aspx");
            }
        }
        protected void ddlLanguage_SelectedIndexChange(object sender, EventArgs e)
        {
            if (cblCategory != null)
            {
                cblCategory.Items.Clear();
                BindCategory(cblCategory, 0, -1, ddlLanguage.SelectedValue);
            }
        }
        protected void ddlLanguageDetail_SelectedIndexChange(object sender, EventArgs e)
        {
            try
            {
                if (Request["p"] != null)
                {
                    PostID = int.Parse(Request["p"].ToString());
                }
                if (PostID > 0)
                {
                    CheckBoxList cblCatDetail = (CheckBoxList)rptDetailPost.Items[0].FindControl("cblCategory");
                    cblCatDetail.Items.Clear();
                    BindCategory(cblCatDetail, 0, -1, ((DropDownList)rptDetailPost.Items[0].FindControl("ddlLanguageDetail")).SelectedValue);
                    SelectCategory(PostID, cblCatDetail);
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("~/admin/Default.aspx");
            }

        }
        /// <summary>
        /// Thêm mới/lưu bài viết
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, CommandEventArgs e)
        {            
            if (Request["post_type"] == null || Request["post_type"] != "page")
            {
                if (cblCategory.SelectedValue == "")
                {
                    lblNotice.Text = "Lỗi: Bạn phải chọn ít nhật một chuyên mục cho bài viết !";
                    return;
                }
                _OPost.Title = txtTitle.Text;
                _OPost.Excerpt = txtExcerpt.Text;
                _OPost.Content = ckeContent.Text;
                _OPost.CreateDate = DateTime.Parse(txtCreateDate.Text, culture, DateTimeStyles.NoCurrentDateDefault);
                _OPost.FeaturedImage = hdfFeaturedImage.Value;
                _OPost.Slug = "";
                _OPost.LangID = ddlLanguage.SelectedValue;
                _OPost.Type = "post";
                _OPost.Status = e.CommandArgument.ToString();
                _OPost.UserCreate = 2;
                List<int> lstCatID = new List<int>();
                foreach (ListItem li in cblCategory.Items)
                {
                    if (li.Selected)
                    {
                        lstCatID.Add(int.Parse(li.Value));
                    }
                }
                if (_BPost.Add(_OPost, lstCatID))
                {
                    Response.Redirect("~/admin/post-new.aspx?post_type=page&p=" + _BPost.GetIDLastRecord().ToString());
                } 
            }
            else {
                _OPost.Title = txtTitle.Text;
                _OPost.Excerpt = "";
                _OPost.Content = ckeContent.Text;
                _OPost.CreateDate = DateTime.Parse(txtCreateDate.Text, culture, DateTimeStyles.NoCurrentDateDefault);
                _OPost.FeaturedImage = "";
                _OPost.Slug = "";
                _OPost.LangID = ddlLanguage.SelectedValue;
                _OPost.Type = "page";
                _OPost.Status = e.CommandArgument.ToString();
                _OPost.UserCreate = 2;
                List<int> lstCatID = new List<int>();
                lstCatID = null;               
                if (_BPost.Add(_OPost, lstCatID))
                {
                    Response.Redirect("~/admin/post-new.aspx?post_type=page&p=" + _BPost.GetIDLastRecord().ToString());
                }
            }
                       
        }

        /// <summary>
        /// Bind chi tiết bài viết vào form cập nhật
        /// </summary>
        /// <param name="PostID"></param>
        
        protected void BindDetailPost(int PostID)
        {
            IList<OPost> lstPostDetail = _BPost.Get(PostID);
            rptDetailPost.DataSource = lstPostDetail;
            rptDetailPost.DataBind();
            ddlLanguage.SelectedValue = lstPostDetail[0].LangID;
            ddlLanguage.DataBind();
            CheckBoxList cblCatDetail = (CheckBoxList)rptDetailPost.Items[0].FindControl("cblCategory");
            BindCategory(cblCatDetail, 0, -1, lstPostDetail[0].LangID);
            SelectCategory(PostID,(CheckBoxList)rptDetailPost.Items[0].FindControl("cblCategory"));
        }

        /// <summary>
        /// Cập nhật bài viết
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rptDetailPost_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Update")
                {
                    if (Request["p"] != null)
                    {
                        PostID = int.Parse(Request["p"].ToString());
                    }
                    if (PostID > 0)
                    {
                        if (Request["post_type"] != null && Request["post_type"].ToString() == "page")
                        {
                            _OPost.PostID = PostID;
                            _OPost.Title = ((TextBox)e.Item.FindControl("txtTitle")).Text;
                            _OPost.Excerpt = "";
                            _OPost.Content = ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeContent")).Text;
                            _OPost.CreateDate = DateTime.Parse(((TextBox)e.Item.FindControl("txtCreateDate")).Text, culture, DateTimeStyles.NoCurrentDateDefault);
                            _OPost.FeaturedImage = "";
                            _OPost.Slug = "";
                            _OPost.LangID = ((DropDownList)e.Item.FindControl("ddlLanguageDetail")).SelectedValue;
                            _OPost.Status = e.CommandArgument.ToString();
                            List<int> lstCatID = new List<int>();
                            lstCatID = null;
                            if (_BPost.Update(_OPost, lstCatID))
                            {
                                rptDetailPage.DataSource = _BPost.Get(PostID);
                                rptDetailPage.DataBind();
                            }
                        }
                        else
                        {
                            _OPost.PostID = PostID;
                            _OPost.Title = ((TextBox)e.Item.FindControl("txtTitle")).Text;
                            _OPost.Excerpt = ((TextBox)e.Item.FindControl("txtExcerpt")).Text;
                            _OPost.Content = ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeContent")).Text;
                            _OPost.CreateDate = DateTime.Parse(((TextBox)e.Item.FindControl("txtCreateDate")).Text, culture, DateTimeStyles.NoCurrentDateDefault);
                            _OPost.FeaturedImage = ((HiddenField)e.Item.FindControl("hdfFeaturedImage")).Value;
                            _OPost.Slug = "";
                            _OPost.LangID = ((DropDownList)e.Item.FindControl("ddlLanguageDetail")).SelectedValue;
                            _OPost.Status = e.CommandArgument.ToString();
                            List<int> lstCatID = new List<int>();
                            if ((CheckBoxList)e.Item.FindControl("cblCategory") != null)
                            {
                                foreach (ListItem li in ((CheckBoxList)e.Item.FindControl("cblCategory")).Items)
                                {
                                    if (li.Selected)
                                    {
                                        lstCatID.Add(int.Parse(li.Value));
                                    }
                                }
                            }
                            if (_BPost.Update(_OPost, lstCatID))
                            {
                                BindDetailPost(_OPost.PostID);
                            }
                        }
                    }
                    else {
                        Response.Redirect("~/admin/Default.aspx");
                    }
                }
                else if (e.CommandName == "SendMail")
                {
                    if (((CheckBox)e.Item.FindControl("cbxSend")).Checked)
                    {

                        string subject = "[subcrible-EnmineKaitlin]-"+((TextBox)e.Item.FindControl("txtTitle")).Text;
                        string content = "<h3>" + ((TextBox)e.Item.FindControl("txtTitle")).Text + "</h3>";
                        content += ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeContent")).Text;
                        //Send email
                        SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                        IList<OEmail> lstEmail = _BEmail.Get(1,100);
                        List<string> lstSendTo = new List<string>();
                        foreach(OEmail objEmail in lstEmail)
                        {
                            lstSendTo.Add(objEmail.Email);            
                        }
                        if (Send_Email(cfg.Network.UserName, lstSendTo, subject, content))
                        {
                            RegisterClientScriptBlock("NOTE", "<script>alert('Đã gửi nội dung bài viết tới email đăng ký');</script>");
                        }
                        else
                        {
                            RegisterClientScriptBlock("NOTE", "<script>alert('Xảy ra lỗi trong quá trình gửi mail vui lòng thử lại !');</script>");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("~/admin/Default.aspx");
            }
        }
        /// <summary>
        /// Bind trạng thái khi lưu bài viết
        /// </summary>
        /// <returns></returns>
        protected string BindCommandArgument()
        {
            return "publish";
        }
        /// <summary>
        /// Bind danh sách chuyên mục vào checkboxlist
        /// </summary>
        protected void BindCategory(CheckBoxList cblCategory, int CatParent,int level,string LangID)
        {
            ListItem li;
            String html="";
            IList<OCategory> lstCategory=_BCategory.Get(0, CatParent,LangID);
            if(lstCategory.Count>0)
            {
                level += 1;
            }
            for (int i = 0; i < level * 3; i++)
            {
                html += "-";   
            }            
            foreach (OCategory objCat in lstCategory)
            {
                if (objCat.CatID != HoiDap_CatID)
                {
                    li = new ListItem(html + objCat.CatName, objCat.CatID.ToString());
                    cblCategory.Items.Add(li);
                    BindCategory(cblCategory, objCat.CatID, level, LangID);
                }
            }
            cblCategory.DataBind();
        }
        protected void SelectCategory(int PostID,CheckBoxList cblCat)
        {
            IList<OCategory_Post> lstCategory_Post = _BCategory_Post.Get(PostID);
            foreach (OCategory_Post objCatPost in lstCategory_Post)
            {
                foreach (ListItem li in cblCat.Items)
                {
                    if (li.Value == objCatPost.IDCat.ToString())
                    {
                        li.Selected = true;
                    }
                }
            }
        }
    }
}
